<template>
  <div class="table-designer-v2 h-full flex flex-col bg-gray-50">
    <!-- 顶部工具栏 -->
    <div class="designer-header bg-white shadow-sm border-b border-gray-200 px-6 py-4">
      <div class="flex items-center justify-between">
        <div class="flex items-center space-x-4">
          <div class="flex items-center space-x-2">
            <el-icon class="text-2xl text-primary">
              <Grid />
            </el-icon>
            <div>
              <h1 class="text-xl font-semibold text-gray-800">
                {{ isNewTable ? '创建新表' : `编辑表: ${tableData.name}` }}
              </h1>
              <p class="text-sm text-gray-500">{{ tab.database }} / {{ databaseTypeLabel }}</p>
            </div>
          </div>
          <el-tag v-if="isModified" type="warning" size="small">已修改</el-tag>
        </div>
        
        <div class="flex items-center space-x-3">
          <!-- 撤销/重做按钮 -->
          <el-button-group>
            <el-tooltip content="撤销 (Ctrl+Z)" placement="bottom">
              <el-button :disabled="!canUndo" @click="undo" size="default">
                <el-icon><RefreshLeft /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="重做 (Ctrl+Y)" placement="bottom">
              <el-button :disabled="!canRedo" @click="redo" size="default">
                <el-icon><RefreshRight /></el-icon>
              </el-button>
            </el-tooltip>
          </el-button-group>
          
          <el-divider direction="vertical" />
          
          <!-- 主要操作按钮 -->
          <el-button @click="previewSQL" size="default">
            <el-icon><View /></el-icon>
            预览SQL
          </el-button>
          <el-button type="primary" @click="saveTable" :loading="isSaving" size="default">
            <el-icon><Check /></el-icon>
            {{ isNewTable ? '创建表' : '保存修改' }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="designer-body flex-1 flex overflow-hidden">
      <!-- 左侧导航 -->
      <div class="designer-nav bg-white border-r border-gray-200 w-36 flex flex-col">
        <div class="nav-header px-4 py-3 border-b border-gray-100">
          <h3 class="text-sm font-medium text-gray-700">表设计选项</h3>
        </div>
        <nav class="nav-items flex-1 overflow-y-auto">
          <a
            v-for="item in navItems"
            :key="item.id"
            :class="[
              'nav-item flex items-center px-4 py-3 text-sm cursor-pointer transition-all duration-200',
              activeSection === item.id 
                ? 'bg-primary-50 text-primary-600 border-l-3 border-primary-500' 
                : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'
            ]"
            @click="activeSection = item.id"
          >
            <el-icon class="mr-3 text-lg">
              <component :is="item.icon" />
            </el-icon>
            <span class="font-medium">{{ item.label }}</span>
            <span 
              v-if="item.count" 
              class="ml-auto text-xs px-2 py-0.5 rounded-full"
              :class="[
                activeSection === item.id 
                  ? 'bg-primary-100 text-primary-700' 
                  : 'bg-gray-100 text-gray-600'
              ]"
            >
              {{ item.count }}
            </span>
          </a>
        </nav>
      </div>

      <!-- 右侧内容区 -->
      <div class="designer-content flex-1 overflow-hidden flex flex-col">
        <!-- 内容区域 -->
        <div class="content-wrapper flex-1 overflow-y-auto">
          <transition name="fade" mode="out-in">
            <!-- 基本信息 -->
            <div v-if="activeSection === 'general'" class="section-content p-6">
              <TableGeneralPanelV2 
                :table-data="tableData"
                :database-type="databaseType"
                @update="handleGeneralUpdate"
              />
            </div>

            <!-- 列设计 -->
            <div v-else-if="activeSection === 'columns'" class="section-content">
              <TableColumnsPanelV2
                :columns="tableData.columns"
                :database-type="databaseType"
                @update="handleColumnsUpdate"
              />
            </div>

            <!-- 索引 -->
            <div v-else-if="activeSection === 'indexes'" class="section-content p-6">
              <TableIndexesPanelV2
                :indexes="tableData.indexes"
                :columns="tableData.columns"
                :database-type="databaseType"
                @update="handleIndexesUpdate"
              />
            </div>

            <!-- 外键 -->
            <div v-else-if="activeSection === 'foreign-keys'" class="section-content p-6">
              <TableForeignKeysPanelV2
                :foreign-keys="tableData.foreignKeys"
                :columns="tableData.columns"
                :database-type="databaseType"
                :connection-id="connectionId"
                @update="handleForeignKeysUpdate"
              />
            </div>

            <!-- 高级选项 -->
            <div v-else-if="activeSection === 'advanced'" class="section-content p-6">
              <TableAdvancedPanelV2
                :options="tableData.advancedOptions"
                :database-type="databaseType"
                @update="handleAdvancedUpdate"
              />
            </div>

            <!-- SQL预览 -->
            <div v-else-if="activeSection === 'sql'" class="section-content p-6">
              <TableSqlPreviewV2
                :table-data="tableData"
                :database-type="databaseType"
                :is-new-table="isNewTable"
                :show-copy-button="true"
                :original-structure="originalStructure"
              />
            </div>
          </transition>
        </div>

        <!-- 底部状态栏 -->
        <div class="status-bar bg-gray-50 border-t border-gray-200 px-6 py-2 flex items-center justify-between text-sm">
          <div class="flex items-center space-x-4 text-gray-600">
            <span>列数: {{ tableData.columns.length }}</span>
            <span v-if="tableData.indexes.length > 0">索引: {{ tableData.indexes.length }}</span>
            <span v-if="tableData.foreignKeys.length > 0">外键: {{ tableData.foreignKeys.length }}</span>
          </div>
          <div class="text-gray-500">
            <span v-if="lastSaved">最后保存: {{ formatTime(lastSaved) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- SQL预览对话框 -->
    <el-dialog
      v-model="showSqlDialog"
      title="SQL预览"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="sql-preview-dialog">
        <TableSqlPreviewV2
          :table-data="tableData"
          :database-type="databaseType"
          :is-new-table="isNewTable"
          :show-copy-button="true"
          :original-structure="originalStructure"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { 
  Grid, 
  Document, 
  List, 
  Link, 
  Setting, 
  View,
  Check,
  RefreshLeft,
  RefreshRight
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useTableStructureStore } from '@/stores/tableStructureStore'
import { useDBServiceStore } from '@/stores/dbService'
import TableGeneralPanelV2 from './table-designer-v2/TableGeneralPanelV2.vue'
import TableColumnsPanelV2 from './table-designer-v2/TableColumnsPanelV2.vue'
import TableIndexesPanelV2 from './table-designer-v2/TableIndexesPanelV2.vue'
import TableForeignKeysPanelV2 from './table-designer-v2/TableForeignKeysPanelV2.vue'
import TableAdvancedPanelV2 from './table-designer-v2/TableAdvancedPanelV2.vue'
import TableSqlPreviewV2 from './table-designer-v2/TableSqlPreviewV2.vue'

// 导入Wails事件系统
let EventsEmit
import('@wailsio/runtime').then(({ EventsEmit: eventsEmit }) => {
  EventsEmit = eventsEmit
}).catch(err => {
  console.error('Failed to import Wails runtime:', err)
})

const props = defineProps({
  tab: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['update'])

// Store实例
const tableStructureStore = useTableStructureStore()
const dbServiceStore = useDBServiceStore()

// 状态管理
const isLoading = ref(false)
const isSaving = ref(false)
const error = ref(null)
const isModified = ref(false)
const lastSaved = ref(null)
const activeSection = ref('general')
const showSqlDialog = ref(false)

// 撤销/重做历史
const history = ref([])
const historyIndex = ref(-1)
const maxHistorySize = 50

// 表数据
const tableData = ref({
  name: '',
  engine: 'InnoDB',
  charset: 'utf8mb4',
  collation: 'utf8mb4_general_ci',
  comment: '',
  columns: [],
  indexes: [],
  foreignKeys: [],
  advancedOptions: {}
})

// 添加一个保存原始结构的变量
const originalStructure = ref(null);

// 计算属性
const connectionId = computed(() => props.tab.connectionId || props.tab.configId)
const databaseType = computed(() => props.tab.data?.databaseType || 'mysql')
const isNewTable = computed(() => props.tab.data?.isNewTable || false)
const canUndo = computed(() => historyIndex.value > 0)
const canRedo = computed(() => historyIndex.value < history.value.length - 1)

// 数据库类型标签
const databaseTypeLabel = computed(() => {
  const labels = {
    mysql: 'MySQL',
    postgresql: 'PostgreSQL',
    sqlite: 'SQLite',
    sqlserver: 'SQL Server',
    dameng: '达梦数据库'
  }
  return labels[databaseType.value] || databaseType.value
})

// 导航项
const navItems = computed(() => {
  const items = [
    { id: 'general', label: '基本信息', icon: Document },
    { id: 'columns', label: '列设计', icon: List, count: tableData.value.columns.length },
    { id: 'indexes', label: '索引', icon: Grid, count: tableData.value.indexes.length }
  ]
  
  // 根据数据库类型添加外键选项
  if (['mysql', 'postgresql', 'sqlserver'].includes(databaseType.value)) {
    items.push({ 
      id: 'foreign-keys', 
      label: '外键约束', 
      icon: Link, 
      count: tableData.value.foreignKeys.length 
    })
  }
  
  // 高级选项
  if (['mysql', 'postgresql'].includes(databaseType.value)) {
    items.push({ id: 'advanced', label: '高级选项', icon: Setting })
  }
  
  // SQL预览
  items.push({ id: 'sql', label: 'SQL预览', icon: View })
  
  return items
})

// 初始化
onMounted(async () => {
  await loadTableStructure()
  setupKeyboardShortcuts()
  
  // 保存初始状态到历史记录
  saveToHistory()
})

// 清理
onBeforeUnmount(() => {
  removeKeyboardShortcuts()
})

// 加载表结构
const loadTableStructure = async () => {
  if (isNewTable.value) {
    initNewTable()
    return
  }
  
  isLoading.value = true
  error.value = null
  
  try {
    const structure = await tableStructureStore.fetchTableStructure({
      configId: connectionId.value,
      database: props.tab.database,
      table: props.tab.table,
      databaseType: databaseType.value
    })
    
    // 保存原始结构
    originalStructure.value = JSON.parse(JSON.stringify(structure));
    
    tableData.value = convertToLocalFormat(structure)
    lastSaved.value = new Date()
    isModified.value = false
    
    // 保存到历史记录
    saveToHistory()
  } catch (err) {
    error.value = err.message
    ElMessage.error(`加载表结构失败: ${err.message}`)
  } finally {
    isLoading.value = false
  }
}

// 初始化新表
const initNewTable = () => {
  tableData.value = getDefaultTableStructure(databaseType.value)
  isModified.value = true
  saveToHistory()
}

// 获取默认表结构
const getDefaultTableStructure = (dbType) => {
  const structure = {
    name: 'new_table',
    comment: '',
    columns: [],
    indexes: [],
    foreignKeys: [],
    advancedOptions: {}
  }
  
  // 根据数据库类型设置默认值
  switch (dbType) {
    case 'mysql':
      structure.engine = 'InnoDB'
      structure.charset = 'utf8mb4'
      structure.collation = 'utf8mb4_general_ci'
      structure.columns.push({
        name: 'id',
        type: 'int',
        length: 11,
        notNull: true,
        primaryKey: true,
        autoIncrement: true,
        comment: '主键'
      })
      break
    case 'postgresql':
      structure.columns.push({
        name: 'id',
        type: 'serial',
        notNull: true,
        primaryKey: true,
        comment: '主键'
      })
      break
    // ... 其他数据库类型
  }
  
  return structure
}

// 处理数据变更
const handleDataChange = () => {
  isModified.value = true
  saveToHistory()
  updateTabData()
}

// 处理基本信息更新
const handleGeneralUpdate = (data) => {
  Object.assign(tableData.value, data)
  handleDataChange()
}

// 处理列更新
const handleColumnsUpdate = (columns) => {
  tableData.value.columns = columns
  handleDataChange()
}

// 处理索引更新
const handleIndexesUpdate = (indexes) => {
  tableData.value.indexes = indexes
  handleDataChange()
}

// 处理外键更新
const handleForeignKeysUpdate = (foreignKeys) => {
  tableData.value.foreignKeys = foreignKeys
  handleDataChange()
}

// 处理高级选项更新
const handleAdvancedUpdate = (options) => {
  tableData.value.advancedOptions = options
  handleDataChange()
}

// 保存到历史记录
const saveToHistory = () => {
  // 如果不在历史末尾，删除当前位置之后的历史
  if (historyIndex.value < history.value.length - 1) {
    history.value = history.value.slice(0, historyIndex.value + 1)
  }
  
  // 添加当前状态到历史
  history.value.push(JSON.parse(JSON.stringify(tableData.value)))
  
  // 限制历史记录大小
  if (history.value.length > maxHistorySize) {
    history.value.shift()
  } else {
    historyIndex.value++
  }
}

// 撤销
const undo = () => {
  if (canUndo.value) {
    historyIndex.value--
    tableData.value = JSON.parse(JSON.stringify(history.value[historyIndex.value]))
    isModified.value = true
  }
}

// 重做
const redo = () => {
  if (canRedo.value) {
    historyIndex.value++
    tableData.value = JSON.parse(JSON.stringify(history.value[historyIndex.value]))
    isModified.value = true
  }
}

// 保存表
const saveTable = async () => {
  if (!validateTable()) return;
  
  // 验证结构修改是否可能有风险
  if (!isNewTable.value) {
    try {
      // 获取原始结构用于比较
      const originalStructure = await tableStructureStore.getStructure;
      
      // 验证结构变更
      const validationResult = await tableStructureStore.validateStructureChange({
        configId: connectionId.value,
        database: props.tab.database,
        table: props.tab.table,
        structure: tableData.value,
        originalStructure: originalStructure,
        isNewTable: isNewTable.value,
        databaseType: databaseType.value
      });
      
      // 如果有警告，显示确认对话框
      if (!validationResult.safe && validationResult.warnings.length > 0) {
        const warningMessages = validationResult.warnings.map(w => 
          `<li class="mb-1">${w.message}<br><span class="text-xs text-gray-500">${w.suggestion || ''}</span></li>`
        ).join('');
        
        try {
          await ElMessageBox.confirm(
            `<p class="mb-2">检测到以下潜在问题:</p><ul class="list-disc pl-5 mb-3">${warningMessages}</ul>
             <p>继续操作可能导致错误或数据丢失，建议先修复这些问题。</p>`,
            '操作风险提示',
            {
              confirmButtonText: '继续保存',
              cancelButtonText: '取消',
              type: 'warning',
              dangerouslyUseHTMLString: true
            }
          );
          // 用户确认继续，下面会执行保存操作
        } catch (e) {
          // 用户取消保存
          return;
        }
      }
    } catch (err) {
      console.error('验证结构失败:', err);
      // 验证失败，但不阻止保存
    }
  }
  
  isSaving.value = true;
  
  try {
    // 保存表结构
    const result = await tableStructureStore.saveTableStructure({
      configId: connectionId.value,
      database: props.tab.database,
      table: tableData.value.name,
      structure: tableData.value,
      isNewTable: isNewTable.value,
      databaseType: databaseType.value,
      originalStructure: await tableStructureStore.getStructure
    });
    
    // 检查是否验证返回而非实际保存
    if (result.validated === true && !result.success) {
      // 显示验证结果
      const warningMessages = result.validationResults.warnings.map(w => 
        `<li class="mb-1">${w.message}<br><span class="text-xs text-gray-500">${w.suggestion || ''}</span></li>`
      ).join('');
      
      ElMessageBox.alert(
        `<p class="mb-2">保存操作取消，存在以下问题需要修复：</p>
         <ul class="list-disc pl-5 mb-3">${warningMessages}</ul>
         <p>请修复这些问题后再尝试保存。</p>`,
        '保存失败',
        {
          type: 'error',
          dangerouslyUseHTMLString: true
        }
      );
      return;
    }
    
    ElMessage.success(isNewTable.value ? '表创建成功' : '表保存成功');
    lastSaved.value = new Date();
    isModified.value = false;
    
    // 更新tab数据
    updateTabData();
    
    // 发送刷新事件，通知其他组件（如连接浏览器）刷新表数据
    if (EventsEmit) {
      try {
        EventsEmit('refresh:table-data', {
          connectionId: connectionId.value,
          database: props.tab.database,
          table: tableData.value.name
        });
        console.log('Sent refresh event for table structure update');
      } catch (error) {
        console.error('Failed to emit refresh event:', error);
      }
    }
  } catch (err) {
    // 错误处理 - 保持原始错误消息不变
    let errorMessage = err.message || '保存失败';
    let errorType = 'error';
    let errorDuration = 5000; 
    
    // 显示原始错误，不做修改
    ElMessage({
      message: errorMessage,
      type: errorType,
      duration: errorDuration,
      showClose: true
    });
    
    // 检查是否有截断错误，如果有，给出额外提示
    if (errorMessage.toLowerCase().includes('truncated')) {
      setTimeout(() => {
        ElMessage({
          message: '提示：数据截断通常是因为减小了字段长度，但现有数据超过了新设置的长度。您可以先修改数据或增加字段长度。',
          type: 'info',
          duration: 8000,
          showClose: true
        });
      }, 1000);
    } else if (errorMessage.toLowerCase().includes('null')) {
      setTimeout(() => {
        ElMessage({
          message: '提示：非空约束问题通常是因为表中已有NULL值。您可以先设置默认值或更新现有数据。',
          type: 'info', 
          duration: 8000,
          showClose: true
        });
      }, 1000);
    }
  } finally {
    isSaving.value = false;
  }
};

// 预览SQL
const previewSQL = () => {
  showSqlDialog.value = true;
  
  // 如果是修改表，根据验证结果显示潜在风险
  if (!isNewTable.value) {
    // 这里可以添加代码来检测和显示潜在的SQL风险
  }
};

// 验证表数据
const validateTable = () => {
  if (!tableData.value.name) {
    ElMessage.error('请输入表名')
    activeSection.value = 'general'
    return false
  }
  
  if (tableData.value.columns.length === 0) {
    ElMessage.error('表至少需要一列')
    activeSection.value = 'columns'
    return false
  }
  
  // 验证列名是否重复
  const columnNames = new Set()
  for (const column of tableData.value.columns) {
    if (!column.name) {
      ElMessage.error('列名不能为空')
      activeSection.value = 'columns'
      return false
    }
    if (columnNames.has(column.name)) {
      ElMessage.error(`列名"${column.name}"重复`)
      activeSection.value = 'columns'
      return false
    }
    columnNames.add(column.name)
  }
  
  return true
}

// 更新tab数据
const updateTabData = () => {
  emit('update', {
    ...props.tab,
    data: {
      ...props.tab.data,
      tableData: tableData.value,
      isModified: isModified.value,
      lastSaved: lastSaved.value
    }
  })
}

// 转换数据格式
const convertToLocalFormat = (apiData) => {
  return {
    name: apiData.name,
    engine: apiData.engine || 'InnoDB',
    charset: apiData.charset || 'utf8mb4',
    collation: apiData.collation || 'utf8mb4_general_ci',
    comment: apiData.comment || '',
    columns: apiData.columns || [],
    indexes: apiData.indexes || [],
    foreignKeys: apiData.foreignKeys || [],
    advancedOptions: apiData.advancedOptions || {}
  }
}

// 格式化时间
const formatTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleString('zh-CN')
}

// 键盘快捷键
const setupKeyboardShortcuts = () => {
  window.addEventListener('keydown', handleKeyDown)
}

const removeKeyboardShortcuts = () => {
  window.removeEventListener('keydown', handleKeyDown)
}

const handleKeyDown = (e) => {
  // Ctrl+Z 撤销
  if (e.ctrlKey && e.key === 'z' && !e.shiftKey) {
    e.preventDefault()
    undo()
  }
  // Ctrl+Y 或 Ctrl+Shift+Z 重做
  else if ((e.ctrlKey && e.key === 'y') || (e.ctrlKey && e.shiftKey && e.key === 'z')) {
    e.preventDefault()
    redo()
  }
  // Ctrl+S 保存
  else if (e.ctrlKey && e.key === 's') {
    e.preventDefault()
    saveTable()
  }
}
</script>

<style lang="scss" scoped>
.table-designer-v2 {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  
  .designer-header {
    backdrop-filter: blur(10px);
    background-color: rgba(255, 255, 255, 0.95);
  }
  
  .designer-nav {
    .nav-item {
      position: relative;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        width: 3px;
        background-color: transparent;
        transition: background-color 0.2s;
      }
      
      &.active::before {
        background-color: var(--el-color-primary);
      }
    }
  }
  
  .content-wrapper {
    background-color: #fafbfc;
  }
  
  .section-content {
    max-width: 1400px;
    margin: 0 auto;
  }
  
  .status-bar {
    font-size: 12px;
    backdrop-filter: blur(10px);
    background-color: rgba(249, 250, 251, 0.95);
  }
  
  // 过渡动画
  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 0.2s ease;
  }
  
  .fade-enter-from,
  .fade-leave-to {
    opacity: 0;
  }
}

// 暗色模式支持
@media (prefers-color-scheme: dark) {
  .table-designer-v2 {
    .designer-header {
      background-color: rgba(31, 41, 55, 0.95);
    }
    
    .designer-nav {
      background-color: #1f2937;
      border-color: #374151;
    }
    
    .content-wrapper {
      background-color: #111827;
    }
    
    .status-bar {
      background-color: rgba(31, 41, 55, 0.95);
    }
  }
}
</style> 